package com.hjy.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hjy.common.utils.PageUtils;
import com.hjy.common.utils.Query;
import com.hjy.product.dao.CategoryBrandRelationDao;
import com.hjy.product.dao.CategoryDao;
import com.hjy.product.entity.CategoryBrandRelationEntity;
import com.hjy.product.vo.categoryVo.category2Level;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hjy.product.entity.CategoryEntity;
import com.hjy.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取三级分类属性目录
     *
     * @return
     */
    @Override
    public List<CategoryEntity> getCategoryListTree() {
        // 1. 首先获取所有的目录
        List<CategoryEntity> list = baseMapper.selectList(null);
        // 2. 通过递归直接获取
        return list.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    // 1. 将当前每个元素的子元素筛选出来
                    categoryEntity.setChildren(getChildren(list, categoryEntity));
                    return categoryEntity;
                }).sorted((o1, o2) -> {
                    if (o1.getSort() != null && o2.getSort() != null) {
                        return o1.getSort() - o2.getSort();
                    }
                    return 0;
                }).collect(Collectors.toList());
    }

    /**
     * 逻辑删除
     *
     * @param asList
     */
    @Override
    public void removeIdsByLogic(List<Long> asList) {
        // TODO 检查当前删除的菜单, 是否被被的地方引入
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 级联更新冗余数据
     * brand
     *
     * @param category
     */
    @Override
    public void updateCascade(CategoryEntity category) {
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setCatelogName(category.getName());
        categoryBrandRelationEntity.setCatelogId(category.getCatId());

        categoryBrandRelationDao.update(categoryBrandRelationEntity,
                new UpdateWrapper<CategoryBrandRelationEntity>().eq("catelog_id", category.getCatId()));
        // TODO 其他级联更新
    }

    public List<CategoryEntity> getChildren(List<CategoryEntity> list, CategoryEntity root) {
        return list.stream().filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(list, categoryEntity));
                    return categoryEntity;
                }).sorted((o1, o2) -> {
                    if (o1.getSort() != null && o2.getSort() != null) {
                        return o1.getSort() - o2.getSort();
                    }
                    return 0;
                }).collect(Collectors.toList());
    }

    @Override
    // sync = true 表示加本地锁
    @Cacheable(value = "category", key = "#root.methodName",sync = true)
    public List<CategoryEntity> getCategoryLevel1() {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_cid", 0);
        return this.list(wrapper);
    }

    /**
     * 使用 redisson 分布式锁优化的获取三级分类数据
     *
     * @return
     */
    public Map<String, List<category2Level>> getCategoryList() {

        Map<String, List<category2Level>> map = null;
        String categoryList = stringRedisTemplate.opsForValue().get("categoryList");
        // 如果为空
        if (StrUtil.isBlank(categoryList)) {
            RLock lock = redissonClient.getLock("categoryList-lock");
            lock.lock();
            // 成功获取锁了
            try {
                // 首先看一下现在缓存里面有东西没, 有东西了就直接返回
                categoryList = stringRedisTemplate.opsForValue().get("categoryList");
                if (StrUtil.isNotBlank(categoryList)) {
                    return JSONUtil.toBean(categoryList, new TypeReference<Map<String, List<category2Level>>>() {
                    }, true);
                }

                System.out.println("缓存未命中, 查询数据库");
                // 执行业务
                map = getCategoryListFromDb();
                if (MapUtil.isEmpty(map)) {
                    // 设置进redis, 这个是用于应对缓存击穿
                    stringRedisTemplate.opsForValue().set("categoryList", "", 20, TimeUnit.SECONDS);
                } else {
                    // 设置进redis
                    stringRedisTemplate.opsForValue().set("categoryList", JSONUtil.toJsonStr(map));
                }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println("缓存命中");
            map = JSONUtil.toBean(categoryList, new TypeReference<Map<String, List<category2Level>>>() {
            }, true);
        }

        return map;
    }

    /**
     * 使用 redis 分布式锁优化的获取三级分类数据
     *
     * @return
     */
    public Map<String, List<category2Level>> getCategoryListDistributed() {

        Map<String, List<category2Level>> map = null;
        String categoryList = stringRedisTemplate.opsForValue().get("categoryList");
        // 锁的特定id
        String lockStr = "";
        // 如果为空
        if (StrUtil.isBlank(categoryList)) {
            // 防止缓存击穿, 加分布式锁, 提供 while 自旋
            while (true) {
                lockStr = UUID.randomUUID().toString();
                Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", lockStr, 300, TimeUnit.SECONDS);
                if (lock) {
                    // 成功获取锁了
                    try {
                        // 首先看一下现在缓存里面有东西没, 有东西了就直接返回
                        categoryList = stringRedisTemplate.opsForValue().get("categoryList");
                        if (StrUtil.isNotBlank(categoryList)) {
                            return JSONUtil.toBean(categoryList, new TypeReference<Map<String, List<category2Level>>>() {
                            }, true);
                        }

                        System.out.println("缓存未命中, 查询数据库");
                        // 执行业务
                        map = getCategoryListFromDb();
                        if (MapUtil.isEmpty(map)) {
                            // 设置进redis, 这个是用于应对缓存击穿
                            stringRedisTemplate.opsForValue().set("categoryList", "", 20, TimeUnit.SECONDS);
                        } else {
                            // 设置进redis
                            stringRedisTemplate.opsForValue().set("categoryList", JSONUtil.toJsonStr(map));
                        }
                    } finally {
                        // 释放锁
                        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                        stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), lockStr);
                    }
                    break;
                } else {
                    // 获取锁失败, 休眠一会儿继续获取
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            System.out.println("缓存命中");
            map = JSONUtil.toBean(categoryList, new TypeReference<Map<String, List<category2Level>>>() {
            }, true);
        }

        return map;
    }

    /**
     * 使用 redis 本地锁优化的获取三级分类数据
     *
     * @return
     */
    public Map<String, List<category2Level>> getCategoryListLocalLock() {
        // 1. 缓存穿透 : 缓存一个有ttl的空值
        // 2. 缓存雪崩 : 给一个随机的ttl值
        // 3. 缓存击穿 : 加锁(本地锁/分布式锁)
        Map<String, List<category2Level>> map = null;
        String categoryList = stringRedisTemplate.opsForValue().get("categoryList");
        // 如果为空
        if (StrUtil.isBlank(categoryList)) {
            // 防止缓存击穿, 加本地锁
            synchronized (this) {
                // 再查一次数据库, 防止多个线程同时进入, 其中一个已经更新缓存的情况
                categoryList = stringRedisTemplate.opsForValue().get("categoryList");
                if (StrUtil.isNotBlank(categoryList)) {
                    return JSONUtil.toBean(categoryList, new TypeReference<Map<String, List<category2Level>>>() {
                    }, true);
                }
                System.out.println("缓存未命中, 查询数据库");
                map = getCategoryListFromDb();
                if (MapUtil.isEmpty(map)) {
                    stringRedisTemplate.opsForValue().set("categoryList", "", 20, TimeUnit.SECONDS);
                } else {
                    // 设置进redis
                    stringRedisTemplate.opsForValue().set("categoryList", JSONUtil.toJsonStr(map));
                }
            }
        } else {
            System.out.println("缓存命中");
            map = JSONUtil.toBean(categoryList, new TypeReference<Map<String, List<category2Level>>>() {
            }, true);
        }

        return map;
    }

    /**
     * 获取三级分类数据
     *
     * @return
     */
    public Map<String, List<category2Level>> getCategoryListFromDb() {
        // 业务优化, 先获取所有数据
        List<CategoryEntity> list = this.list();

        // 获取第一层级的数据
        List<CategoryEntity> category1List = getParent_cid(list, 0L);
        Map<String, List<category2Level>> collect1 = category1List.stream().collect(Collectors.toMap(categoryEntity -> categoryEntity.getCatId().toString(), l1 -> {
            List<CategoryEntity> category2List = getParent_cid(list, l1.getCatId());
            List<category2Level> list2 = category2List.stream().map(l2 -> {
                category2Level category2Level = new category2Level(l1.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                List<CategoryEntity> category3List = getParent_cid(list, l2.getCatId());
                List<com.hjy.product.vo.categoryVo.category2Level.category3Level> collect = category3List.stream().map(l3 -> {
                    return new category2Level.category3Level(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                }).collect(Collectors.toList());
                category2Level.setCatalog3List(collect);
                return category2Level;
            }).collect(Collectors.toList());
            return list2;
        }));

        return collect1;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> list, Long id) {
        return list.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == id;
        }).collect(Collectors.toList());
    }

}